﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Clipboard.Model;
using Clipboard.Model.Enum;
using Clipboard.Model.Interface;
using Clipboard.Services;
using Clipboard.Tools;
using Clipboard.ViewModel;
using HandyControl.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Win32;
using SqlSugar;
using Window = System.Windows.Window;

namespace Clipboard
{
    /// <summary>
    /// LoginPage.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow : Window
    {
        private bool _isSending = false;
        private int _countdown = 60;
        private Timer _timer;
        private readonly SqlSugarScope _db;  // 注入 SqlSugarHelper
        public LoginViewModel ViewModel;

        public LoginWindow(LoginViewModel viewModel, SqlSugarHelper sqlSugarHelper)
        {
            // 设置 DataContext 为 ViewModel
            DataContext = viewModel;
            _db = sqlSugarHelper.Db;
            ViewModel = viewModel;
            InitializeComponent();
        }


        private void Close_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();                 
        }

        private void Captcha_Click(object sender, RoutedEventArgs e)
        {
            // 确保邮箱格式正确
            string email = EmailTextBox.Text;
            if (string.IsNullOrEmpty(email) || !email.Contains("@"))
            {
                Growl.Error($"邮箱有误");
                return;
            }

            // 防止重复发送
            if (_isSending)
                return;

            _isSending = true;

            //验证码关闭
            CountdownProgressBar.IsEnabled = false;

            // 启动验证码发送逻辑
            _ = SendVerificationEmailAsync(email);

            // 启动动画显示验证码输入框、提示信息、进度条

            // 启动倒计时
            _timer = new Timer(TimerCallback, null, 0, 1000);

            _isSending = false;
        }


        private async Task SendVerificationEmailAsync(string email)
        {
            // 这里模拟发送邮件，可以根据实际需要调用邮件发送接口
            var result = await new Services.EmailService().SendVerificationCodeAsync(email);
            if (result)
            {
                Growl.Success($"验证码已发送至 {email}，请查收。");
            }
            else
            {
                Growl.Error($"验证码发送失败，请重试。");
                CountdownProgressBar.IsEnabled = true;
                CountdownProgressBar.Content = "验证码";
            }
            // 模拟网络请求延迟
            await Task.Delay(2000);
        }

        private void TimerCallback(object state)
        {
            // 在UI线程更新倒计时
            Dispatcher.Invoke(() =>
            {
                if (_countdown > 0)
                {
                    CountdownProgressBar.Content = _countdown;
                    _countdown--;
                }
                else
                {
                    ResetCaptcha();
                }
            });
        }

        private void ResetCaptcha()
        {
            if (_timer != null)
                _timer.Dispose();
            CountdownProgressBar.IsEnabled = true;
            _countdown = 60;
            CountdownProgressBar.Content = "验证码";
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            string emailText = EmailTextBox.Text;
            string password = PasswordBox.Password;
            string code = Code.Text;

            var result = new Services.EmailService().ValidateVerificationCode(emailText, code);

            if (!result)
            {
                ResetCaptcha();
                Growl.Error($"验证码错误");
                return;
            }

            await ViewModel.LoginAsync(emailText, password);


            // 创建登录窗口实例
            //ClipboardViewModel clipboardViewModel = App.AppHost.Services.GetRequiredService<ClipboardViewModel>();

            //MainWindow mainWindow = new MainWindow(clipboardViewModel);

            ////// 以模态方式显示登录窗口
            //bool? cc = mainWindow.ShowDialog();
            //this.Close();

            this.DialogResult = true;

            // Add further logic here based on the result of the query
        }
      
    }
}
